/*
 * NetworkThreadManager.java
 *
 * Created on 6 maart 2008, 19:17
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package racer.client.network;

import java.io.*;
import java.net.*;
import racer.client.data.*;
import racer.client.gui.Game;
import racer.client.gui.main.Pling_prefWindowView;
import racer.client.network.threads.GoingToServerThread;
import racer.client.network.threads.IncomingFromServerThread;
import racer.client.network.interfaces.INetworkThreadManager;
import java.util.HashMap;

//import threads2.client.threads.Gui;

/**
 *
 * @author Lieven
 */
public class NetworkThreadManager implements INetworkThreadManager{
	public static PositionMessage posmess;
	public static SettingsMessage settingsmess;
	public static LoginMessage loginmess;
	public static ChatMessage chatmess;
	public static Socket clientSocket = null;
	public static PrintStream os = null;
	public static DataInputStream is = null;
	public static BufferedReader inputLine = null;
	public static boolean closed = false;
	public static ThreadGroup networkThreadGroup;
	private static Thread[] threadArray;
	private static String host;
	private static int port_number;
	private Game game = null;
	private Pling_prefWindowView prefWindow;
	public HashMap<String,String> settingsmap;
	
	private int playerid;

	/**
	 * Creates a new instance of NetworkThreadManager
	 */
	//public NetworkThreadManager(int port_number,String host, Game game) {
	public NetworkThreadManager(int port_number,String host, Pling_prefWindowView prefWindow) {
		//set port and host
		this.host=host;
		this.port_number=port_number;
		//this.game = game;
		this.prefWindow = prefWindow;

		initNetwork();
		initThreads();

		settingsmap = new HashMap<String,String>();
		loginmess = new LoginMessage();
	}


	/**
	 * NETWORK INIT
	 */
	public void initNetwork(){
		//al op voorhand geset
		//int port_number=2222;
		//String host="localhost";

		// Initialization section:
		// Try to open a socket on a given host and port
		// Try to open input and output streams
		try {
			clientSocket = new Socket(host, port_number);
			inputLine = new BufferedReader(new InputStreamReader(System.in));
			os = new PrintStream(clientSocket.getOutputStream());
			is = new DataInputStream(clientSocket.getInputStream());

		} catch (UnknownHostException e) {
			System.err.println("Don't know about host "+host);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for the connection to the host "+host);
		}
	}

	public void sendMessage(NetworkMessage msg) {
		
	}
	
	/*
	public void sendLoginMessage() {
		os.print(loginmess.getFormedMessage());
	}*/
	
	public void sendPositionToServer(double xvalue,double yvalue,int angle,int active_tile){
		os.print(posmess.getFormedMessage(xvalue,yvalue,angle,active_tile));
	}

	public void sendListRacesRequest() {
		os.print(":=:6;fromID=" + playerid + ":=:");
	}
	/*
	public void sendListRacesRequest(int raceid, String mapname, int numplayers, int maxplayers) {
		os.print(":=:6;fromID=4;raceID=3;mapName=2;numPlayers=2;maxPlayers=4:=:");
	}*/
	
	public void sendCreateRaceMessage(String mapName, int maxPlayers) {
		os.print(":=:4;fromID=" + playerid 
				+ ";mapName=" + mapName
				+ ";maxPlayers=" + maxPlayers 
				+ ":=:");
	}
	
	public void sendJoinRaceMessage(int raceid) {
		os.print(":=:5;fromID=" + this.playerid
				+ ";raceID=" + raceid
				+ ":=:");
	}
	
	public void sendGameOverMessage() {
		os.print(":=:8;fromID=" + this.playerid
				+ ":=:");
	}
	
	public void sendMapMessage(String mapName, String map) {
		os.print(":=:10;mapName=" + mapName
				+ ";mapString=" + map
				+ ":=:");
	}

	public void sendChatMessageToServer(int toID,String text){
		os.print(chatmess.getFormedMessage(toID,text));
	}     

	public void sendSettingMessageToServer(int toID,String settingtext){
		os.print(settingsmess.getFormedMessage(toID,settingtext));
	}          

	public void sendAllSettingsToServer(){
		//
	}
	/*THREADS MANAGER
	 *
	 *
	 **/

	public void initThreads(){

		threadArray = new Thread[5];
		networkThreadGroup = new ThreadGroup ("NetworkThreads");
		Thread incomingFromServerThread = new Thread ( networkThreadGroup, new IncomingFromServerThread(this));
		incomingFromServerThread.setName("incomingFromServerThread");
		Thread goingToServerThread = new Thread ( networkThreadGroup, new GoingToServerThread(this));
		goingToServerThread.setName("goingToServerThread");

		incomingFromServerThread.start();        
		goingToServerThread.start();
		//set active threads ..copy into array..for later use
		setActiveThreads();
		//print threadarray
		//for (int i = 0; i < threadArray.length; i++){
		//    os.println(threadArray[i]);
		//}
	}

	public int getNumberOfActiveThreads(){
		return networkThreadGroup.activeCount();
	}    

	public void setActiveThreads(){
		networkThreadGroup.enumerate(threadArray);
	}
	public void stopNetworkThreads(){
		networkThreadGroup.stop();
	}

	public void setNetworkThreadsPriority(int np){
		networkThreadGroup.setMaxPriority(np);
	}

	// Create an array of threads, to hold all of the active threads

	public Game getGame(){
		return this.game;
	}
	public void setGame(Game game) {
		this.game = game;
	}
	public Pling_prefWindowView getPrefWindow() {
		return this.prefWindow;
	}

	public void setMessageIDs(int id){
		//message is the form used to send data through the network
		//argument is client ID (voor later)
		//int nickid = Integer.parseInt(settingsmap.get("nickid"));
		this.playerid = id;
		posmess=new PositionMessage(playerid);        
		chatmess=new ChatMessage(playerid);
		settingsmess=new SettingsMessage(playerid);
	}
	public void setSetting(String setID,String setValue){
		//save settings +send them
		settingsmap.put(setID,setValue);
	}
	
}



